//
//  ZPFAdvertisingView.m
//  ZPFHimalayan
//
//  Created by zhou on 2018/11/27.
//  Copyright © 2018 MissZhou. All rights reserved.
//

#import "ZPFAdvertisingView.h"

@interface ZPFAdvertisingView ()
@property (nonatomic, strong) UIImageView *advImageView;
@property (nonatomic, strong) UIButton *countBtn;
@property (nonatomic, strong) NSTimer *countTimer;
@property (nonatomic, assign) int count;
@property (nonatomic, copy) TapBlock tapBlock;
@end

//广告显示时间5s
static int const showTime = 5;

@implementation ZPFAdvertisingView

- (NSTimer *)countTimer{
    if (!_countTimer) {
        _countTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    }
    return _countTimer;
}


#pragma mark - 响应事件
- (void)countDown{
    _count--;
    [_countBtn setTitle:NSStringFormat(@"跳过%d",_count) forState:UIControlStateNormal];
    if (_count == 1) {
        [self disMiss];
    }
}

- (void)tapPushAdvertis{
    [self disMiss];
    if (self.tapBlock) {
        self.tapBlock();
    }
    //跳转到广告详情：下载或者链接
}

- (void)show{
     //倒计时方法1：GCD
    [self startCoundown];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
}

// GCD倒计时
- (void)startCoundown
{
    __block int timeout = showTime + 1; //倒计时时间 + 1
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self disMiss];
                
            });
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_countBtn setTitle:[NSString stringWithFormat:@"跳过%d",timeout] forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame withTapBlock:(TapBlock)tapBlock{
    if (self = [super initWithFrame:frame]) {
        //1、广告图
        _advImageView = [[UIImageView alloc] initWithFrame:frame];
        _advImageView.userInteractionEnabled = YES;
        _advImageView.contentMode = UIViewContentModeScaleAspectFill;
        _advImageView.clipsToBounds = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPushAdvertis)];
        [_advImageView addGestureRecognizer:tap];
        
        //移除按钮
        CGFloat btnW = 60/WIDTH_5S_SCALE;
        CGFloat btnH = 30/WIDTH_5S_SCALE;
        _countBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - btnW - 15/WIDTH_5S_SCALE, SafeAreaTopStateHeight + 10/WIDTH_5S_SCALE , btnW, btnH)];
        [_countBtn addTarget:self action:@selector(disMiss) forControlEvents:UIControlEventTouchUpInside];
        [_countBtn setTitle:[NSString stringWithFormat:@"跳过%d", showTime] forState:UIControlStateNormal];
        _countBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_countBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _countBtn.backgroundColor = [UIColor colorWithRed:38 /255.0 green:38 /255.0 blue:38 /255.0 alpha:0.6];
        _countBtn.layer.cornerRadius = 4;
        
        [self addSubview:_advImageView];
        [self addSubview:_countBtn];
        
        //判断沙盒中是否存在图片，存在直接显示
        NSString *filePath = [self getFilePathWithImageName:[[NSUserDefaults standardUserDefaults] valueForKey:adverImageName]];
        BOOL isExist = [self isFileExistWithFilePath:filePath];
        if (isExist) {
            //图片存在
            [self setFilePath:filePath];
            self.tapBlock = tapBlock;
            [self show];
        }
        // 2.无论沙盒中是否存在广告图片，都需要重新调用广告接口，判断广告是否更新
        [self getAdvertisingImage];
    }
    return self;
}

/**
 移除广告页
 */
- (void)disMiss{
    [self.countTimer invalidate];
    self.countTimer = nil;
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

/**
 根据图片拼接路径

 @param imageName 图片名
 @return 图片路径
 */
- (NSString *)getFilePathWithImageName:(NSString *)imageName{
    if (imageName) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        return filePath;
    }
    return nil;
}

/**
 判断文件是否存在

 @param filePath 文件
 @return 是否存在
 */
- (BOOL)isFileExistWithFilePath:(NSString *)filePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = false;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}

- (void)setFilePath:(NSString *)filePath{
    _filePath = filePath;
    _advImageView.image = [UIImage imageWithContentsOfFile:filePath];
}

- (void)getAdvertisingImage{
    NSArray *imageArray = @[@"http://imgsrc.baidu.com/forum/pic/item/9213b07eca80653846dc8fab97dda144ad348257.jpg", @"http://pic.paopaoche.net/up/2012-2/20122220201612322865.png", @"http://img5.pcpop.com/ArticleImages/picshow/0x0/20110801/2011080114495843125.jpg", @"http://www.mangowed.com/uploads/allimg/130410/1-130410215449417.jpg"];
    NSString *imageUrl = imageArray[arc4random() % imageArray.count];
    
    NSArray *stringArr = [imageUrl componentsSeparatedByString:@"/"];
    NSString *imageName = stringArr.lastObject;
    // 拼接沙盒路径
    NSString *filePath = [self getFilePathWithImageName:imageName];
    BOOL isExist = [self isFileExistWithFilePath:filePath];
    if (!isExist){// 如果该图片不存在，则删除老图片，下载新图片
        
        [self downloadAdImageWithUrl:imageUrl imageName:imageName];
        
    }
}

/**
 *  下载新图片
 */
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        
        NSString *filePath = [self getFilePathWithImageName:imageName]; // 保存文件的名称
        
        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {// 保存成功
            NSLog(@"广告页保存成功");
            [self deleteOldImage];
            [[NSUserDefaults standardUserDefaults] setValue:imageName forKey:adverImageName];
            [[NSUserDefaults standardUserDefaults] synchronize];
            // 如果有广告链接，将广告链接也保存下来
        }else{
            NSLog(@"广告页保存失败");
        }
        
    });
}

/**
 *  删除旧图片
 */
- (void)deleteOldImage
{
    NSString *imageName = [[NSUserDefaults standardUserDefaults] valueForKey:adverImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}
@end
